import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // 让每个请求携带自定义token
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response.data
  },
  error => {
    console.log('err' + error) // for debug
    // 判断是否是会话到期
    if (error.response !== undefined && error.response.status === 401) {
      MessageBox.confirm('会话过期，请重新登录', '确认退出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '退出',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    } else {
      let m = error.message
      if (error.response !== undefined && error.response.data !== undefined) {
        m = parseErrorMessage(error.response.data) || m
      }

      Message({
        message: m,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

function code2Message(code) {
  if (code === undefined) {
    return '请求失败'
  }

  switch (code) {
    case 'Unauthorized':
      return '会话过期，请确认是否已经登录。'
    case 'NoSuchUser':
      return '用户不存在。'
    case 'UserLocked':
      return '用户被锁定。'
    case 'LoginFailed':
      return '登录失败，用户名不存在或密码错误。'
    case 'InvalidParameter':
      return '输入参数错误。'
    case 'InternalServerError':
      return '服务器返回错误。'
    case 'Forbidden':
      return '权限不足，请确认是否有该操作权限。'
    case 'DataAccessError':
      return '数据库查询失败。'
    case 'FileExisted':
      return '文件已经存在。'
    case 'NumberFormatException':
      return '数据格式错误，请检查输入的数据类型是否正常。'
    case 'Duplicated':
      return '记录重复，请重新输入。'
    case 'UserConflict':
      return '用户名已经存在，请重新输入。'
    case 'Unauthenticated':
      return '密码错误。'
    default:
      return code
  }
}

export function parseErrorMessage(text) {
  if (text === undefined) {
    return undefined
  }

  let o = text
  if (typeof text === 'string') {
    o = JSON.parse(text)
  }

  if (o === undefined || o.code === undefined) {
    return undefined
  }

  return code2Message(o.code) || ((o.code || '请求失败') + ': ' + o.message)
}

export default service
